const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const config = require('./config.js');
const envConfig = require('./env/config_development.json');

const expressJwt = require('express-jwt');


// view engine setup
// app.set(path.join(path.resolve(__dirname, '..'), 'views'));
// app.set('view engine', 'ejs');

app.set('views',path.join(__dirname,'views'));
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static('public'));

const loginInterceptor = require('../interceptor/login.interceptor');

app.use(envConfig.NJ_DOM_FS.context,loginInterceptor);

const statusInterceptor = require('../interceptor/status.interceptor');

app.use(envConfig.NJ_DOM_FS.context,statusInterceptor);

config.getGlobbedFiles(path.join(path.resolve(__dirname, '..'), 'routes/**/*.js')).forEach(function(routePath) {
    require(path.resolve(routePath))(router);
});

app.use(envConfig.NJ_DOM_FS.context, router);

app.use("/api*",expressJwt({ secret: envConfig.secret}).unless({path: [
    '/api/merchants/login',
    '/api/merchants/register'
]}));

app.use(function (req, res, next) {
    console.log("aa");
    const err = new Error('Not Found');
    err.status = 404;
    // next(err);
    res.json({status: 404, message: "page not found"});
});

app.use(function (err, req, res, next) {
    // set locals, only providing error in development

    //jwt error

    if (err.name === 'UnauthorizedError') {
        return res.status(403).send({
            code:-1,
            message: 'No token provided.'
        });
    }

    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    console.log(err);
    // render the error page
    res.status(err.status || 500);
    // res.render('error');
    res.json({status: 500, message: "server error"});
});
const notify = require('../socket.io/notify');
app.notify = function (server){
    notify.prepareSocketIO(server);
};

exports = module.exports = app;
